﻿using eLoan.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace eLoan.Controllers
{
    public class LoanTypeController : BaseController
    {
        public ActionResult AddEdit(int? id)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.LoanTypes);

                var db = new DatabaseContext();
                var loanTypeModel = new LoanTypeModel();

                if (id == null)
                {
                    
                    loanTypeModel.DBCommand = AdministrationHelper.DBCommand.Add.ToString();

                    return View("AddEdit", loanTypeModel);
                }
                else
                {
                    loanTypeModel.DBCommand = AdministrationHelper.DBCommand.Edit.ToString();

                    var loanTypes = db.LoanTypes;
                    var loanType = loanTypes.Where(w => w.ID == id).SingleOrDefault<LoanType>();
                    loanTypeModel.LoanType = loanType;


                    return View("AddEdit", loanTypeModel);
                }
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }

        [HttpPost]
        public ActionResult Save(LoanType loanType, string command)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.LoanTypes);

                if (ModelState.IsValid)
                {
                    using (var db = new DatabaseContext())
                    {
                        if (command == AdministrationHelper.DBCommand.Add.ToString())
                        {
                            db.LoanTypes.Add(loanType);
                            db.SaveChanges();
                        }
                        else if (command == AdministrationHelper.DBCommand.Edit.ToString())
                        {
                            db.Entry(loanType).State = System.Data.EntityState.Modified;
                            db.SaveChanges();
                        }
                        else
                        {
                            // cancelled
                        }
                    }
                }

                return RedirectToAction("LoanTypes", "Administration");
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }
    }
}
